package com.settlement.system.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.util.SecurityUtils;
import com.settlement.system.common.util.common.BeanValidator;
import com.settlement.system.common.util.common.CommonAcsUtil;
import com.settlement.system.common.util.common.SystemUserUtil;
import com.settlement.system.mapper.BaseMapper;
import com.settlement.system.mapper.TblAcsPermissonOrderSourceMapper;
import com.settlement.system.mapper.TblAcsPermissonRoleMapper;
import com.settlement.system.mapper.security.userdetails.SysUserDetails;
import com.settlement.system.model.entity.common.SystemUser;
import com.settlement.system.model.entity.common.TblAcsPermissonOrderSource;
import com.settlement.system.model.entity.common.TblAcsPermissonRole;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.ITblAcsPermissonOrderSourceService;
import com.settlement.system.service.ITblAcsPermissonRoleService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 权限角色组表 服务实现类
 *
 * @author he.xx
 * @since 2021-07-06
 */
@Service
@Slf4j
public class TblAcsPermissonRoleServiceImpl extends BaseServiceImpl implements ITblAcsPermissonRoleService {

    @Resource
    private TblAcsPermissonRoleMapper tblAcsPermissonRoleMapper;

    @Resource
    private TblAcsPermissonOrderSourceMapper tblAcsPermissonOrderSourceMapper;

    @Override
    public BaseMapper init() {
        return tblAcsPermissonRoleMapper;
    }

    @Resource
    private ITblAcsPermissonOrderSourceService tblAcsPermissonOrderSourceService;

    @Override
    public ObjectDataResponse importOrderSourceFile(MultipartFile file, HttpServletRequest request, String permissonRoleId) {
        String errorMessage = null;
        List<String> errorMessageList = null;
        try {
            ImportDataListener listener = new ImportDataListener();
            ExcelReaderBuilder builder = EasyExcel.read(file.getInputStream(), TblAcsPermissonOrderSource.class, listener);
            builder.doReadAll();
            errorMessage = listener.getErrorMessage();
            if (listener.rowCount == 0) {
                errorMessage = "导入内容为空";
            }
        } catch (Exception ex) {
            log.error("导入订单来源权限，批量导入数据，导入转化出错", ex);
            errorMessage = "系统异常,请联系管理员";
        }
        if (StringUtils.isEmpty(errorMessage)) {
            return new ObjectDataResponse(ReturnStatusEnum.IMPORT_SUCCESS.getValue(), "导入成功");
        }
        errorMessageList = new ArrayList<>();
        errorMessageList.add(errorMessage);
        return new ObjectDataResponse<List>(errorMessageList, ReturnStatusEnum.IMPORT_ERROR.getValue(), errorMessage);
    }

    public class ImportDataListener<ModelType> extends AnalysisEventListener<ModelType> {
        private String errorMessage = null;
        private List<TblAcsPermissonOrderSource> dataList = new ArrayList<TblAcsPermissonOrderSource>();
        private int rowCount = 0;

        @Override
        public void invoke(ModelType modelType, AnalysisContext analysisContext) {
            modelType = BeanValidator.clearBeanStringBlank(modelType);
            if (modelType == null) {
                return;
            }
            SysUserDetails user = SecurityUtils.getUser();;
            TblAcsPermissonOrderSource tblAcsPermissonOrderSource = (TblAcsPermissonOrderSource) modelType;
            tblAcsPermissonOrderSource.setId(CommonAcsUtil.generateUUId());
            tblAcsPermissonOrderSource.setCreateTime(new Date());
            tblAcsPermissonOrderSource.setCreateUser(user.getUsername());
            tblAcsPermissonOrderSource.setUpdateTime(new Date());
            tblAcsPermissonOrderSource.setUpdateUser(user.getUsername());
            if (StringUtils.isBlank(tblAcsPermissonOrderSource.getPermissionRoleCode()) || StringUtils.isBlank(tblAcsPermissonOrderSource.getThirdSourceNo())) {
                errorMessage = "第" + (dataList.size() + 2) + "行数据，有必填项，请核实";
            }
            if (StringUtils.isBlank(errorMessage)) {
                TblAcsPermissonRole tblAcsPermissonRoleQueryVo = new TblAcsPermissonRole();
                tblAcsPermissonRoleQueryVo.setRoleCode(tblAcsPermissonOrderSource.getPermissionRoleCode());
                TblAcsPermissonRole tblAcsPermissonRole = tblAcsPermissonRoleMapper.getPermissionRoleInfo(tblAcsPermissonRoleQueryVo);
                if (tblAcsPermissonRole == null) {
                    errorMessage = "第" + (dataList.size() + 2) + "行数据，角色组编码不存在，请核实";
                }
            }
            if (StringUtils.isBlank(errorMessage)) {
                List<TblAcsPermissonOrderSource> tblAcsPermissonOrderSourceList = tblAcsPermissonOrderSourceMapper.selectByModel(tblAcsPermissonOrderSource);
                if (CollectionUtils.isEmpty(tblAcsPermissonOrderSourceList)) {
                    dataList.add(tblAcsPermissonOrderSource);
                }
            }
            rowCount++;
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            try {
                batchSaveImportOrderSourcePermission(dataList);
                dataList.clear();
            } catch (Exception e) {
                log.error("权限角色组设置，批量导入订单来源权限，批量导入保存失败", e);
                if (StringUtils.isEmpty(e.getMessage())) {
                    errorMessage = "导入异常，请联系管理管理员";
                } else {
                    errorMessage = e.getMessage();
                }
            }
        }

        @Override
        public boolean hasNext(AnalysisContext context) {
            if (StringUtils.isEmpty(errorMessage)) {
                return true;
            }
            return false;
        }

        public String getErrorMessage() {
            return errorMessage;
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void batchSaveImportOrderSourcePermission(List<TblAcsPermissonOrderSource> dataList) {
        log.info("导入订单来源权限，批量保存，dataList=" + dataList);
        if (!CollectionUtils.isEmpty(dataList)) {
            tblAcsPermissonOrderSourceService.batchSave(dataList);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public boolean deletePermissionRole(TblAcsPermissonRole model) {
        tblAcsPermissonRoleMapper.deleteById(model);
        TblAcsPermissonOrderSource tblAcsPermissonOrderSource = new TblAcsPermissonOrderSource();
        tblAcsPermissonOrderSource.setPermissionRoleCode(model.getRoleCode());
        tblAcsPermissonOrderSourceMapper.deleteByRoleCode(tblAcsPermissonOrderSource);
        return true;
    }

    @Override
    public TblAcsPermissonRole getPermissionRoleInfo(TblAcsPermissonRole model) {
        return tblAcsPermissonRoleMapper.getPermissionRoleInfo(model);
    }

    @Override
    public boolean updateById(TblAcsPermissonRole model) {
        SystemUserUtil.setDefualt(model);
        int num = tblAcsPermissonRoleMapper.updateById(model);
        if (num > 0) {
            return true;
        }
        return false;
    }
}

